#!/bin/bash
# CMDB 日志查看脚本

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

LOG_DIR="$SCRIPT_DIR/logs"
BACKEND_LOG="$LOG_DIR/backend.log"
FRONTEND_LOG="$LOG_DIR/frontend.log"

# 显示使用说明
show_usage() {
    echo -e "${CYAN}=========================================="
    echo "   CMDB - 日志查看工具"
    echo -e "==========================================${NC}"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  backend, b     - 查看后端日志"
    echo "  frontend, f    - 查看前端日志"
    echo "  all, a         - 查看所有日志"
    echo "  follow         - 实时跟踪所有日志"
    echo "  clear          - 清空所有日志"
    echo ""
    echo "示例:"
    echo "  $0 backend     - 显示后端最后50行日志"
    echo "  $0 follow      - 实时查看所有日志"
    echo ""
}

# 查看后端日志
view_backend() {
    if [ -f "$BACKEND_LOG" ]; then
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${CYAN}🔧 后端日志 (最后50行):${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        tail -n 50 "$BACKEND_LOG"
    else
        echo -e "${RED}✗ 后端日志文件不存在: $BACKEND_LOG${NC}"
    fi
}

# 查看前端日志
view_frontend() {
    if [ -f "$FRONTEND_LOG" ]; then
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        echo -e "${CYAN}🎨 前端日志 (最后50行):${NC}"
        echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
        tail -n 50 "$FRONTEND_LOG"
    else
        echo -e "${RED}✗ 前端日志文件不存在: $FRONTEND_LOG${NC}"
    fi
}

# 实时跟踪日志
follow_logs() {
    echo -e "${CYAN}=========================================="
    echo "   实时日志 (Ctrl+C 退出)"
    echo -e "==========================================${NC}"
    echo ""
    
    if [ -f "$BACKEND_LOG" ] && [ -f "$FRONTEND_LOG" ]; then
        tail -f "$BACKEND_LOG" "$FRONTEND_LOG"
    elif [ -f "$BACKEND_LOG" ]; then
        tail -f "$BACKEND_LOG"
    elif [ -f "$FRONTEND_LOG" ]; then
        tail -f "$FRONTEND_LOG"
    else
        echo -e "${RED}✗ 没有找到任何日志文件${NC}"
        exit 1
    fi
}

# 清空日志
clear_logs() {
    echo -e "${YELLOW}⚠️  确定要清空所有日志吗? (y/n): ${NC}"
    read -r confirm
    if [ "$confirm" = "y" ]; then
        > "$BACKEND_LOG" 2>/dev/null
        > "$FRONTEND_LOG" 2>/dev/null
        echo -e "${GREEN}✓ 日志已清空${NC}"
    else
        echo -e "${YELLOW}已取消${NC}"
    fi
}

# 主逻辑
case "${1:-all}" in
    backend|b)
        view_backend
        ;;
    frontend|f)
        view_frontend
        ;;
    all|a)
        view_backend
        echo ""
        view_frontend
        ;;
    follow)
        follow_logs
        ;;
    clear)
        clear_logs
        ;;
    help|h|-h|--help)
        show_usage
        ;;
    *)
        show_usage
        exit 1
        ;;
esac
